package com.bj58.mis.apm.server.core.util;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class ParameterUtils {
	public static Integer toInteger(Object n){
		if(n==null){
			return null;
		}
		if(n instanceof Number){
			return ((Number)n).intValue();
		}else if(n instanceof String){
			String strN = (String)n;
			if(!strN.isEmpty()){
				return Integer.parseInt(strN);
			}
			return null;
		}
		return null;
	}
	public static Long toLong(Object n){
		if(n==null){
			return null;
		}
		if(n instanceof Number){
			return ((Number)n).longValue();
		}else if(n instanceof String){
			String strN = (String)n;
			if(!strN.isEmpty()){
				return Long.parseLong(strN);
			}
			return null;
		}
		return null;
	}
	public static Double toDouble(Object n){
		if(n==null){
			return null;
		}
		if(n instanceof Number){
			return ((Number)n).doubleValue();
		}else if(!n.toString().trim().isEmpty()){
			return Double.parseDouble(n.toString().trim());
		}else{
			return null;
		}
	}
	public static Integer getInteger(Map<String, Object> params, String key){
		return toInteger(params.get(key));
	}
	public static Integer getInteger(Map<String, Object> params, String key, int defaultValue){
		Integer value = getInteger(params, key);
		if(value==null){
			return defaultValue;
		}
		return value;
	}
	public static Long getLong(Map<String, Object> params, String key){
		return toLong(params.get(key));
	}
	public static Double getDouble(Map<String, Object> params, String key){
		return toDouble(params.get(key));
	}
	@SuppressWarnings("unchecked")
	public static <T> T getValue(Map<String, Object> params, String key){
		if(params==null){
			return null;
		}
		return (T) params.get(key);
	}
	
	public static String join(List<Integer> list){
		StringBuilder result = new StringBuilder();
		for(Integer item : list){
			if(result.length()>0){
				result.append(",");
			}
			result.append(item);
		}
		return result.toString();
	}
	
	public static int getOffset(Map<String, Object> params){
		Integer page = getInteger(params, "page", 1);
		Integer limit = getLimit(params);
		return (page-1)*limit;
	}
	public static int getLimit(Map<String, Object> params){
		Integer limit = getInteger(params, "rows", 20);
		return limit;
	}
	
	
	public static String getLLikeValue(String val) {
		if(StringUtils.isEmpty(val)) {
			return null;
		}
		return "%" + escapeValue(val);
	}
	public static String getRLikeValue(String val) {
		if(StringUtils.isEmpty(val)) {
			return null;
		}
		return escapeValue(val) + "%";
	}
	public static String getBLikeValue(String val) {
		if(StringUtils.isEmpty(val)) {
			return null;
		}
		return "%" + escapeValue(val) + "%";
	}
	public static String escapeValue(String value) {
		String tar = value;
		if (tar.contains("/")) {
			tar = tar.replaceAll("/", "//");
		}
		if (tar.contains("%") || tar.contains("_")) {
			tar = tar.replaceAll("%", "/%").replaceAll("_", "/_");
		}
		return tar;
	}
}
